package org.example.system.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 响应验证码图片
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/validcode")
    public void validCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(220, 100,4,10);
        String code = lineCaptcha.getCode();//获得生成的验证码
        log.info("--------AuthController | validCode | code:{}",code);
        String clientUid = request.getParameter("clientUid");//客户端id
        log.info("--------AuthController | validCode | clientUid:{}",clientUid);
        //存储到redis缓存
        String key = "LOGIN_VALID_CODE:" + clientUid;
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);//验证码5分钟有效
        //输出图片给浏览器
        lineCaptcha.write(response.getOutputStream());
        response.getOutputStream().flush();//把缓存中的图片数据刷新出去
    }
}
